var redis = require('./redis');
const { promisify } = require("util");
const getAsync = promisify(redis.get).bind(redis);
const existsAsync = promisify(redis.exists).bind(redis);
var _ = require('lodash');
var { isArray } = require('./tools')


var exists = async function (cacheName, key) {
  var count = await existsAsync(getReidsKey(cacheName, key))
  return count > 0
}
exports.exists = exists;

var get = async function (cacheName, key) {
  var data = await getAsync(getReidsKey(cacheName, key))
  data = JSON.parse(data);
  return data
};

exports.get = get;

var set = function (cacheName, key, value, time, callback) {
  if (typeof time === 'function') {
    callback = time;
    time = null;
  }
  callback = callback || _.noop;
  value = JSON.stringify(value);
  if (!time) {
    redis.set(getReidsKey(cacheName, key), value, callback);
  } else {
    //将毫秒单位转为秒
    redis.setex(getReidsKey(cacheName, key), parseInt(time / 1000), value, callback);
  }
};

var remove = function (cacheName, key) {
  if (!isArray(key)) {
    key = [key]
  }
  for (let i = 0; i < key.length; i++) {
    try {
      redis.del(getReidsKey(cacheName, key[i]))
    } catch (err) {
      console.error(err)
    }
  }
}

exports.remove = remove;

/**
 * cmdb::instance::5ee8372a12b3904a483f26f9
 */
var getReidsKey = function (cacheName, bizKey) {
  return "cmdb::" + cacheName + "::" + bizKey
}

exports.set = set;
